package com.wzh.codegen.biz.controller;

import com.wzh.codegen.api.domain.dto.DatasourceQuery;
import com.wzh.codegen.biz.domain.dto.DatasourceDTO;
import com.wzh.codegen.biz.service.DatasourceService;
import com.wzh.common.general.result.PageQuery;
import com.wzh.common.general.result.PageResult;
import com.wzh.common.general.result.Result;
import com.wzh.common.mybatis.util.MybatisPageUtils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 * 数据源管理控制器，提供数据源的配置和管理接口
 * </p>
 *
 * @author 山归岿
 * @create 2025-06-15-19:42
 */
@Tag(name = "数据源管理", description = "数据源管理相关接口")
@RestController
@RequestMapping("/datasource")
@RequiredArgsConstructor
public class DatasourceController {

    private final DatasourceService datasourceService;

    @Operation(summary = "分页查询数据源")
    @PostMapping("/page")
    public Result<PageResult<DatasourceDTO>> page(@RequestBody PageQuery<DatasourceQuery> pageQuery) {
        PageResult<DatasourceDTO> result = datasourceService.page(pageQuery);
        return Result.success(result);
    }


    @Operation(summary = "获取所有数据源")
    @GetMapping("/list")
    public Result<List<DatasourceDTO>> list() {
        List<DatasourceDTO> result = MybatisPageUtils.convertList(datasourceService.list(), DatasourceDTO.class);
        return Result.success(result);
    }

    @Operation(summary = "根据ID获取数据源")
    @GetMapping("/{id}")
    public Result<DatasourceDTO> getById(@PathVariable Long id) {
        DatasourceDTO result = datasourceService.getByIdVo(id);
        return Result.success(result);
    }

    @Operation(summary = "创建数据源")
    @PostMapping
    public Result<Void> create(@Valid @RequestBody DatasourceDTO dto) {
        datasourceService.create(dto);
        return Result.success();
    }

    @Operation(summary = "更新数据源")
    @PutMapping
    public Result<Void> update(@Valid @RequestBody DatasourceDTO dto) {
        datasourceService.update(dto);
        return Result.success();
    }

    @Operation(summary = "删除数据源")
    @DeleteMapping("/{id}")
    public Result<Void> delete(@PathVariable Long id) {
        datasourceService.delete(id);
        return Result.success();
    }

    @Operation(summary = "测试数据源连接")
    @PostMapping("/test")
    public Result<String> testConnection(@Valid @RequestBody DatasourceDTO dto) {
        String result = datasourceService.testConnection(dto);
        return Result.success(result);
    }

}